/*
 * This file (Function.java) is protected by the GNU GPL licence (v2). 
 * Please read the license.txt attached for further informations. 
 * 
 */
package org.algoristes.alkwarel.script;

/**
 * @author Xavier Gouchet
 * 
 */
public class ScriptFunction extends ScriptVariable {

	private String[] mParameters;

	/**
	 * Constructor
	 * 
	 * @param name
	 *            name of the function
	 * @param params
	 *            parameter names of the function
	 * @param def
	 *            definition of the function
	 * @param depth
	 *            depth at which the variable is declared
	 */
	public ScriptFunction(String name, String[] params, String def, int depth) {
		super(name, def, depth);
		if (params != null)
			mParameters = params;
		else
			mParameters = new String[] {};
	}

	/**
	 * @param params
	 * @param depth
	 * @return the result of the function
	 */
	public String evalFunction(String[] params, int depth) {

		if ((params == null) && (mParameters.length != 0))
			throw new RuntimeException("Number of arguments mismatch");

		if (params.length != mParameters.length)
			throw new RuntimeException("Number of arguments mismatch");

		ScriptVariable var;
		for (int i = 0; i < params.length; i++) {
			var = new ScriptVariable(mParameters[i], params[i], depth + 1);
			ScriptParser.getVariablesStore().put(var);
		}

		ScriptParser parser = new ScriptParser(depth + 1);
		return parser.runScript(mValue);
	}

	/**
	 * @return the name of the function
	 */
	public String getName() {
		return mName;
	}

	public String toString() {
		String str = mName;
		for (String p : mParameters)
			str += " " + p;
		str += " {\n" + mValue + "\n}";
		return str;
	}
}
